package cc.rengu.redp.bizimpl.upmp.controller;


import cc.rengu.igas.bomp.facade.BompMchntManageService;
import cc.rengu.igas.bomp.facade.bean.SysParamBean;
import cc.rengu.igas.bomp.facade.request.ParamQueryRequest;
import cc.rengu.igas.bomp.facade.response.ParamQueryResponse;
import cc.rengu.redp.bizimpl.bean.FieldInfo;
import cc.rengu.redp.bizimpl.constant.UpmpConstant;
import cc.rengu.redp.bizimpl.enums.BizDataAuditStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizOprEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.igas.bean.CompareBean;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.*;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 刘玉亮.LL
 */
@Api(tags = "商户管理:集团商户管理")
@Slf4j
@RestController
@RequestMapping(value = "/admin/merParam/marketInfo")
public class MarketInfoController extends BaseController {
    private long oprMenuId = 1;
    private String oprMenuName = "商户管理:集团商户管理";
    private long chkMenuId = 2;
    private String chkMenuName = "商户管理:集团商户管理";
    private String webNextUrl = "/admin/merParam/marketInfo/edit";

    private final static Logger logger = LoggerFactory.getLogger(MarketInfoController.class);

    @Autowired
    private IMarketInfoService marketInfoService;

    @Autowired
    private IUpmpSysParamService upmpSysParamService;

    @Autowired
    private IUpmpOrganizationService organizationService;
    @Autowired
    private IUpmpSysSeqService upmpSysSeqService;
    
    @Autowired
    private IndustryInfoService industryInfoService;

    @Resource
    private RegionInfoService regionInfoService;

    @Autowired
    private IBizTmpService bizTmpService;

    @Autowired
    private IUpmpBMchntBaseInfoService bMchntBaseInfoService;

    @DubboReference(version = "${dubbo.protocol.version}", check = false)
    private BompMchntManageService mchntManageService;
    
    @GetMapping(value = "/list")
    public Map<String, Object> findByPage(QueryRequest request, MarketInfo entity) {
        return getDataTable(this.marketInfoService.findByPage(request, entity));
    }
    
    @GetMapping(value = "/edit")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "主键", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String")
    })
    public Map<String, Object> editShow(@ModelAttribute("platMchntInfo") MarketInfo entity, Model model, HttpServletRequest request) throws RedpException {
        Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        LinkedHashMap<String, String> isMap = new LinkedHashMap<String, String>();
        isMap.put("1", "是");
        isMap.put("0", "否");
        String optFlag = request.getParameter("optFlag") == null ? "" : request.getParameter("optFlag");
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        // 增加
        if ("add".equals(optFlag)) {
            String instId = request.getParameter("instId") == null ? "" : request.getParameter("instId");
            String crtOrgId = "";
            if (user.isAdmin()) {
                if (StringUtils.isEmpty(instId)) {
                    log.error("运营中心管理员新增数据必须先选择法人行！");
                    throw new RedpException("运营中心管理员新增数据必须先选择法人行！");
                } else {
                    UpmpOrganization headOrg = organizationService.getHeadOrgByCode(instId);
                    crtOrgId = (headOrg == null ? user.getOrgCode() : headOrg.getOrgCode());
                }
            } else {
                instId = (instId == null ? user.getInstId() : instId);
                crtOrgId = user.getOrgCode();
            }
            UpmpOrganization org = organizationService.getOrgByCode(crtOrgId, instId);
            entity.setId("0");
            entity.setGroupMchntNo(BusinessContainer.INIT_MCHNT_NO);
            entity.setIsMassReceive("0");
            entity.setInstId(instId);
            entity.setGroupMchntStatus(BusinessContainer.status_01);
            entity.setCrtOrgName(org.getOrgName());

            ParamQueryRequest instprovincereq = new ParamQueryRequest();
            instprovincereq.setUserId(user.getId());
            instprovincereq.setParamKey(instId);
            instprovincereq.setParamType("INST_PROVINCE");
            ParamQueryResponse queryResponse = bMchntBaseInfoService.paramQuery(instId, instprovincereq, bMchntBaseInfoService.genMerOrder(instId));
            List<SysParamBean> sysParamList1 = queryResponse.getSysParamList();
            if (CollectionUtils.isNotEmpty(sysParamList1)) {
                entity.setRegisterProvince(sysParamList1.get(0).getParamValue());
            }
        }
        // 修改，注销，停用，启用，详情，审批
        List<CompareBean> compareBeans = new ArrayList<>();
        if ("upd".equals(optFlag) || "cancel".equals(optFlag) || "stop".equals(optFlag) ||
                "use".equals(optFlag) || "detail".equals(optFlag) || "chk".equals(optFlag)) {
            String id = request.getParameter("id") == null ? "" : request.getParameter("id");

            if (!"".equals(id)) {
// 审核：获取临时表数据并转换成实体对象
                if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag) || PageOptFlagEnum.OPT_FLAG_CHECK_VIEW.getType().equals(optFlag)) {
                    BizTmp tmp = bizTmpService.getById(id);
                    if (Common.isBlank(tmp)) {
                        logger.error("根据id没有找到指定临时表数据！");
                        throw new RedpException("根据id没有找到指定临时表数据！");
                    }
                    String bizdata = "";
                    if (null != tmp.getBizData1()) {
                        bizdata += tmp.getBizData1();
                    }
                    if (null != tmp.getBizData2()) {
                        bizdata += tmp.getBizData2();
                    }
                    if (null != tmp.getBizData3()) {
                        bizdata += tmp.getBizData3();
                    }
                    entity = JSON.parseObject(bizdata, MarketInfo.class);

                    //临时表中操作为修改的话，比对差异数据
                    if (BizOprEnum.OPR_UPDATE.getType().equals(tmp.getBizOpr())){
                        MarketInfo formalEntity = marketInfoService.getById(id);
                        compareBeans = combare(entity, formalEntity);
                    }
                    if(PageOptFlagEnum.OPT_FLAG_CHECK_VIEW.getType().equals(optFlag)){
                        optFlag = "details";
                    }
                } else {
                    entity = marketInfoService.getById(id);
                }

                if (Common.isBlank(entity)) {
                    logger.error("根据id没有找到指定数据！");
                    throw new RedpException("根据id没有找到指定数据！");
                }
                List<IndustryInfo> industryInfos = industryInfoService.findByIndustryType(entity.getCupsMcc(),"01");
                if (null != industryInfos && industryInfos.size() > 0) {
                    IndustryInfo industryInfo = industryInfos.get(0);
                    entity.setMerGrpNo(industryInfo.getGrpNo());
                }

                UpmpOrganization organization = organizationService.getOrgByCode(entity.getCrtOrgId(), entity.getInstId());
                entity.setCrtOrgName(organization.getOrgName());
            } else {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常！");
            }

        }

        result.put("isMassReceive", entity.getIsMassReceive());
        // 国家代码：156-CHN
        entity.setNationCd("156");
        result.put("entity", entity);
        result.put("groupMchntNo", entity.getGroupMchntNo());
        result.put("optFlag", optFlag);
//		result.put("mangName", entity.getMangName());
        result.put("compareBeans",JSON.toJSONString(compareBeans));
        return result;
    }

    private List<CompareBean> combare(MarketInfo tmpObj, MarketInfo formalObj) throws RedpException {
        List<CompareBean> compareBeans = new ArrayList<>();
        Field[] fields = tmpObj.getClass().getDeclaredFields();
        if (Common.isNotBlank(fields)) {
            for (Field field : fields) {
                FieldInfo tmpField = CommonUtils.getFieldValueByFieldName(field.getName(), tmpObj);
                FieldInfo formalField = CommonUtils.getFieldValueByFieldName(field.getName(), formalObj);

                if ("merGrpNo".equals(field.getName())) {
                    List<IndustryInfo> industryInfos = industryInfoService.findByIndustryType(formalObj.getCupsMcc(),"00");
                    if (null != industryInfos && industryInfos.size() > 0) {
                        IndustryInfo industryInfo = industryInfos.get(0);
                        formalField.setValue(industryInfo.getGrpNo());
                    }
                }

                if (!tmpField.getValue().equals(formalField.getValue())) {
                    CompareBean compareBean = new CompareBean();
                    String name = field.getName();
                    String value = formalField.getValue();
                    if ("crtOrgName".equals(name)) {
                        continue;
                    } else if ("isReceiveRadio".equals(name)) {
                        if ("1".equals(value)) {
                            compareBean.setValue("是");
                        } else if ("0".equals(value)) {
                            compareBean.setValue("否");
                        } else {
                            compareBean.setValue(value);
                        }
                    } else if ("licenceType".equals(name)) {
                        if ("01".equals(value)) {
                            compareBean.setValue("企业");
                        } else if ("02".equals(value)) {
                            compareBean.setValue("个体");
                        } else if ("03".equals(value)) {
                            compareBean.setValue("分支机构");
                        } else if ("04".equals(value)) {
                            compareBean.setValue("非企业法人");
                        } else {
                            compareBean.setValue(value);
                        }
                    } else if ("registerCapital".equals(name)) {
                        if ("1".equals(value)) {
                            compareBean.setValue("10万以下");
                        } else if ("2".equals(value)) {
                            compareBean.setValue("10万-100万");
                        } else if ("3".equals(value)) {
                            compareBean.setValue("100万-500万");
                        } else if ("4".equals(value)) {
                            compareBean.setValue("500万-1000万");
                        } else if ("5".equals(value)) {
                            compareBean.setValue("10000万以上");
                        } else {
                            compareBean.setValue(value);
                        }
                    } else if ("managementScope".equals(name)) {
                        if ("01".equals(value)){
                            compareBean.setValue("餐饮、宾馆、娱乐、珠宝金饰、工艺美术品类）");
                        } else if ("02".equals(value)){
                            compareBean.setValue("房地产汽车类");
                        } else if ("03".equals(value)){
                            compareBean.setValue("百货、中介、培训、景区门票等");
                        } else if ("04".equals(value)){
                            compareBean.setValue("批发类商户");
                        } else if ("05".equals(value)){
                            compareBean.setValue("加油、超市类");
                        } else if ("06".equals(value)){
                            compareBean.setValue("交通运输售票");
                        } else if ("07".equals(value)){
                            compareBean.setValue("水电气缴费");
                        } else if ("08".equals(value)){
                            compareBean.setValue("政府类");
                        } else if ("09".equals(value)){
                            compareBean.setValue("便民类");
                        } else if ("10".equals(value)){
                            compareBean.setValue("公立医院、公立学校、慈善");
                        } else if ("11".equals(value)){
                            compareBean.setValue("宾馆餐娱类");
                        } else if ("12".equals(value)){
                            compareBean.setValue("房地产汽车类");
                        } else if ("13".equals(value)){
                            compareBean.setValue("批发类");
                        } else if ("14".equals(value)){
                            compareBean.setValue("超市加油类");
                        } else if ("15".equals(value)){
                            compareBean.setValue("一般类商户");
                        } else if ("16".equals(value)){
                            compareBean.setValue("三农商户");
                        } else {
                            compareBean.setValue(value);
                        }
                    } else if ("settleAcctType".equals(name)) {
                        if ("01".equals(value)) {
                            compareBean.setValue("本行对公账户／卡号");
                        } else if ("02".equals(value)) {
                            compareBean.setValue("本行对私账户／卡号");
                        } else {
                            compareBean.setValue(value);
                        }
                    }else if("acctOpenProvince".equals(name)||"acctOpenCity".equals(name)||"acctOpenArea".equals(name)||"registerProvince".equals(name)||"registerCity".equals(name)||"registerArea".equals(name)){
                        RegionInfo oneByCode = regionInfoService.findOneByCode(value, "01");
                        if(Common.isNotBlank(oneByCode)){
                            compareBean.setValue(oneByCode.getRegionName());
                        }else{
                            compareBean.setValue(value);
                        }
                    } else {
                        compareBean.setValue(value);
                    }
                    compareBean.setName(name);
                    compareBeans.add(compareBean);
                }
            }
        }
        return compareBeans;
    }

 
    
    //@RequiresPermissions("商户管理:集团商户管理")
    @PostMapping(value = "/edit")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "主键", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String")
    })
    public OperationResult editSave(@ModelAttribute("MarketInfo") MarketInfo entity, Model model, HttpServletRequest request) throws RedpException {
        String optFlag = request.getParameter("optFlag") == null ? "" : request.getParameter("optFlag");

        String menuId;
        if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {
            menuId = String.valueOf(chkMenuId);
        } else {
            menuId = String.valueOf(oprMenuId);
            if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(optFlag)) {
                entity.setGroupMchntNo(genCode());
            }
        }
        return marketInfoService.saveData(menuId, oprMenuName, entity, request, webNextUrl);
    }

    
    //@RequiresPermissions("商户管理:集团商户管理")
    @DeleteMapping("/{ids}")
    public void delete(@PathVariable String ids) throws RedpException {
        String[] idsArr = ids.split(StringPool.COMMA);
        for (String s : idsArr) {
            MarketInfo entity = marketInfoService.getById(s);
            if (!BizDataAuditStatusEnum.AUDIT_STATUS_ADD_REJECT.getType().equals(entity.getAuditStatus())) {
                throw new RedpException("非新增审批拒绝的集团商户，不能进行删除");
            }
        }
        this.marketInfoService.getBaseMapper().deleteBatchIds(Arrays.asList(idsArr));
    }
    /**
     * 生成 [ 集团商户 ] 编号：“GRP” + 4位年份 + 8位顺序号
     *
     * @return
     */
    public String genCode() {
        // 固定入参
        String common = "COMM_PARAM_CODE";
        // 集团商户编号前缀
        String prefix = "GRP";
        // 渠道ID：固定值20
        String instId = upmpSysParamService.getById(UpmpConstant.IGAS_DEFAULT_INST_ID).getPrimaryValue();
        // 获取渠道ID：固定20
        String channelId = CommonUtils.getChannelId(upmpSysParamService, instId);
        // 生成序列号
        String serialNumber = upmpSysSeqService.updateParamValue(common, prefix, channelId);
        // 8位日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        String date4 = sdf.format(new Date());
        // 编码：GRP + 4位日期 + 8位顺序编号
        String result = prefix + date4 + String.format("%08d", Integer.parseInt(serialNumber));
        return result;
    }

    /**
     * 查询省、市、县区
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/provinceSelect2List", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "q", value = "参数", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String")
    })
    public String provinceSelect2List(HttpServletRequest request, @NotBlank(message = "required") String instId) {
        String q = request.getParameter("q");
        if (null == q) {
            return null;
        }
        q = q.replaceAll("&amp;", "&");
        String[] param = q.split("&");
        if (param.length > 1) {
            return JSON.toJSONString(CommonUtils.dataDictToSelect2(upmpSysParamService, param[1],instId));
        } else {
            return JSON.toJSONString(CommonUtils.dataDictToSelect2(upmpSysParamService, param[0],instId));
        }
    }

    public static boolean isEmpty(Object object) {
        String str = (String) object;
        if ("".equals(str) || null == str) {
            return true;
        }
        return false;
    }
}
